﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using JJServices.FileService.Interface;

namespace JJServices.FileService.Concrete
{
    public class FileService : IFileService
    {
        public string ApplicationPath { get; set; }


        /// <summary>
        /// Save the contents of the Stream to a file
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fs"></param>
        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }

        #region IFileService Members

        public void DeleteFile(string path)
        {
            if (File.Exists(ApplicationPath + "/" + path))
                File.Delete(ApplicationPath + "/" + path);
        }

        public void MoveFile(string source, string destination)
        {
            File.Move(ApplicationPath + "/" + source ,ApplicationPath + "/" + destination);
        }

        public void AppendFile(System.IO.Stream stream, string path)
        {

            using (FileStream fs = File.Open(ApplicationPath + "/" + path, FileMode.Append))
            {
                SaveFile(stream, fs);
                fs.Close();
            }
        }

        public bool FolderExists(string path)
        {
            return Directory.Exists(ApplicationPath + "/" + path);
        }

        public void CreateFolder(string path)
        {
            Directory.CreateDirectory(ApplicationPath + "/" + path);
        }

        public IList<string> FilesInDirectory(string path)
        {
            IList<string> filenames = new List<string>();
  

            DirectoryInfo di = new DirectoryInfo(ApplicationPath + "/" + path);
            foreach (FileInfo fi in di.GetFiles())
            {
                filenames.Add(fi.Name);
            }

            return filenames;
        }

        #endregion
    }
}
